<?php

namespace App\Models;

use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;


/*展览model*/

class CodeGuideExhibition extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';


    protected $table = 'code_guide_exhibition';

    protected $guarded = []; //使用模型  update 更新时，允许被全部更新，若不写，则会报错 或 没任何数据变化


    /**
     * 列表
     * @param page int 页码
     * @param limit int 分页大小
     * @param keywords string 搜索关键词
     * @param is_play string 是否发布  1 发布  2 未发布
     * @param create_start_time datetime 活动创建开始时间   数据格式 年月日时分秒
     * @param create_end_time datetime 活动创建结束时间
     * @param time_status 是否验证时间状态  1 验证  2 不验证
     */
    public function lists($field, $keywords = null, $is_play = null,$time_status=null, $create_start_time = null, $create_end_time = null, $limit = 10)
    {
        if (empty($field)) {
            $field = ['id', 'name', 'img', 'start_time', 'end_time', 'intro', 'qr_url', 'browse_num', 'is_play', 'create_time'];
        }
        $res = $this->select($field)
            ->where(function ($query) use ($keywords) {
                if ($keywords) {
                    $query->where('name', 'like', "%$keywords%");
                }
            })->where(function ($query) use ($create_start_time, $create_end_time, $is_play,$time_status) {
                if ($create_start_time && $create_end_time) {
                    $query->whereBetween('create_time', [$create_start_time, $create_end_time]);
                }
                //状态
                if (!empty($is_play)) {
                    $query->where('is_play', $is_play);
                }
                if ($time_status == 1) {
                    $query->where('start_time', '<=', date('Y-m-d H:i:s'))->where('end_time', '>', date('Y-m-d H:i:s'));
                }
            })
            ->where('is_del', 1)
            ->orderByDesc('id')
            ->paginate($limit)
            ->toArray();
        return $res;
    }

    /**
     * 详情
     * @param id int 展览id
     */
    public function detail($id, $qr_code = null, $is_play = null, $field = null)
    {
        if (empty($field)) {
            $field = ['id', 'name', 'img', 'start_time', 'end_time', 'intro', 'qr_url', 'browse_num', 'is_play', 'create_time','qr_code','qr_url'];
        }
        $res = $this->select($field)
            ->where('is_del', 1)
            ->where(function ($query) use ($id, $qr_code, $is_play) {
                if ($id) {
                    $query->where('id', $id);
                }
                if ($qr_code) {
                    $query->where('qr_code', $qr_code);
                }
                if ($is_play) {
                    $query->where('is_play', $is_play);
                }
            })
            ->first();
        return $res;
    }
}
